<template>

  
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="formInline.leavename" placeholder="请输入申请人姓名" clearable />
    </el-form-item>

    <el-form-item label="申请状态">
      <el-select
        v-model="formInline.state"
        placeholder="请选择"
        clearable
      >
        <el-option label="待审核" :value="1" />
        <el-option label="已通过" :value="2" />
        <el-option label="已驳回" :value="3" />
      </el-select>
    </el-form-item>
    <el-form-item label="创建日期">
      <el-date-picker
        v-model="formInline.statetime"
        type="date"
        placeholder="年/月/日"
        value-format="YYYY-MM-DD"
      />至
      <el-date-picker
        v-model="formInline.endtime"
        type="date"
        placeholder="年/月/日"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="success" @click="dialogTableVisible = true">
        申请
      </el-button>
   
    </el-form-item>
  </el-form>


  <el-table
    :data="tableData"
    style="width: 100%"
    :row-class-name="tableRowClassName"
  >
    <el-table-column type="index" label="编号" width="60px"/>
    <el-table-column prop="applicationName" label="姓名"/>
    <el-table-column prop="departmentId" label="部门">
      <template v-slot="a">
        <span v-if="a.row.departmentId==1">IT信息部</span>
        <span v-if="a.row.departmentId==2">人力资源部</span>
        <span v-if="a.row.departmentId==3">财务部</span>
        <span v-if="a.row.departmentId==4">销售部</span>
        <span v-if="a.row.departmentId==5">行政部</span>
      </template>
    </el-table-column>
    <el-table-column prop="leaveTypeName" label="请假类别"/>
    <el-table-column prop=" " label="请假时间" width="190px">
      <template v-slot="a">
        <span>{{ moment(a.row.startTime).format("YYYY-MM-DD") }}至{{ moment(a.row.endTime).format("YYYY-MM-DD") }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="totalTime" label="总工时(H)" width="90px"/>
    <el-table-column prop="reportTime" label="报到时间" width="100px">
    <template v-slot="a">
        <span>{{ moment(a.row.reportTime).format("YYYY-MM-DD") }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="reason" label="请假事由"/>
    <el-table-column prop="depleaders" label="部门领导" />
    <el-table-column prop="stateName" label="审批状态"/>
    <el-table-column prop="leaveReview" label="审核原因"/>
    <el-table-column prop="createDate" label="创建时间" width="100px">
      <template v-slot="a">
        <span>{{ moment(a.row.createDate).format("YYYY-MM-DD") }}</span>
      </template>
    </el-table-column>
    <el-table-column prop=" " label="操作" width="230px">
      <template v-slot="a">
        <el-button type="danger" v-if="a.row.applicationName==currentloginname&&a.row.state==1" @click="Del(a.row.id)">删除</el-button>
        <el-button type="primary" v-if="a.row.applicationName==currentloginname&&a.row.state==1" @click="edit(a.row)">修改</el-button>
        <el-button type="warning" v-if="currentloginname==courrentleaders&&a.row.state==1" @click="shenhe(a.row)">审批</el-button>
      </template>
    </el-table-column>
  </el-table>

  <table>
            <tr>
                <td>
                    <el-pagination
                    v-model:current-page="page.pageindex"
                    v-model:page-size="page.pagesize"
                    :page-sizes="[15,20,30]"
                    :size="size"
                    background="true"
                    layout="slot, sizes"
                    :total="page.totalCount"
                    >
                    共{{ page.totalCount }}条 每页显示{{ page.pagesize }}条  当前第{{ page.pageindex }}页/共{{ page.totalPage }}页
                    </el-pagination>
                </td>
                <td>
                    <el-pagination
                    v-model:current-page="page.pageindex"
                    v-model:page-size="page.pagesize"
                    :page-sizes="[15,20,30]"
                    :size="size"
                    background="true"
                    layout="slot, prev, pager, next"
                    :total="page.totalCount"
                    prev-text="上一页"
                    next-text="下一页"
                    >
                    <el-button :disabled="page.pageindex==1" @click="page.pageindex=1">首页</el-button>
                    </el-pagination>
                </td>
                <td>
                    <el-pagination
                    v-model:current-page="page.pageindex"
                    v-model:page-size="page.pagesize"
                    :page-sizes="[15,20,30]"
                    :size="size"
                    background="true"
                    layout="slot,jumper"
                    :total="page.totalCount"
                    >
                    <el-button :disabled="page.pageindex==page.totalPage" @click="page.pageindex=page.totalPage">尾页</el-button>
                    </el-pagination>
                </td>
            </tr>
  </table>





  <!-- 提交申请 -->
 <el-dialog v-model="dialogTableVisible" title="申请提交" width="800">
     <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="姓名:" prop="applicationName">
          <el-input v-model="ruleForm.applicationName" />
        </el-form-item>
        <el-form-item label="部门:" prop="departmentId">
          <el-select v-model="ruleForm.departmentId" placeholder="请选择">
            <el-option 
          v-for="(label, value) in {1:'IT信息部',2:'人力资源部',3:'财务部',4:'销售部',5:'行政部'}" 
          :key="value"
          :label="label" 
          :value="value" />
          </el-select>
        </el-form-item>
      
        
        <el-form-item label="请假类别" prop="leaveTypeId">
          <el-radio-group v-model="ruleForm.leaveTypeId">
            <el-radio v-for="item in leavelist" :value="item.id" name="type">
              {{ item.leaveTypeName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="请假时间">
          <span class="newline-span">
            <span>自
              <input type="datetime-local" v-model="ruleForm.startTime" @change="calculateTotalTime">
            至
            <input type="datetime-local" v-model="ruleForm.endTime" @change="calculateTotalTime">
          
          </span><br>
          <span>共计{{ruleForm.days}}</span><br>
          <span>报道时间:
            <input type="datetime-local" v-model="ruleForm.reportTime">
          </span>
          </span>
        </el-form-item>

        <el-form-item label="请假事由" prop="reason">
          <el-input v-model="ruleForm.reason" type="textarea" />
        </el-form-item>

        <el-form-item label="部门领导:" prop="depleaders">
          <el-input v-model="ruleForm.depleaders" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
  </el-dialog>



  <!-- 修改申请 -->
 <el-dialog v-model="dialogTableVisibleUpdate" title="申请编辑" width="800">
     <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="姓名:" prop="applicationName">
          <el-input v-model="ruleForm.applicationName" />
        </el-form-item>
        <el-form-item label="部门:" prop="departmentId">
          <el-select v-model="ruleForm.departmentId" placeholder="请选择">
            <el-option label="IT信息部" :value="1" />
            <el-option label="人力资源部" :value="2" />
            <el-option label="财务部" :value="3" />
            <el-option label="销售部" :value="4" />
            <el-option label="行政部" :value="5" />
            </el-select>
        </el-form-item>
      
        
        <el-form-item label="请假类别" prop="leaveTypeId">
          <el-radio-group v-model="ruleForm.leaveTypeId">
            <el-radio v-for="item in leavelist" :value="item.id" name="type">
              {{ item.leaveTypeName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="请假时间">
          <span class="newline-span">
            <span>自
              <input type="datetime-local" v-model="ruleForm.startTime" @change="calculateTotalTime">
            至
            <input type="datetime-local" v-model="ruleForm.endTime" @change="calculateTotalTime">
          
          </span><br>
          <span>共计{{ruleForm.days}}</span><br>
          <span>报道时间:
            <input type="datetime-local" v-model="ruleForm.reportTime">
            
          </span>
          </span>
        </el-form-item>

        <el-form-item label="请假事由" prop="reason">
          <el-input v-model="ruleForm.reason" type="textarea" />
        </el-form-item>

        <el-form-item label="部门领导:" prop="depleaders">
          <el-input v-model="ruleForm.depleaders" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">
            修改
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
  </el-dialog>

<!-- 审核 -->
  <el-dialog v-model="dialogTableVisibleShenHe" title="审核" width="800">
     <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="姓名:" prop="applicationName">
          {{ ruleForm.applicationName }}
        </el-form-item>
        <el-form-item label="部门:" prop="departmentId">
          {{ ruleForm.departmentId==1?"IT信息部":ruleForm.departmentId==2?"人力资源部":ruleForm.departmentId==3?"财务部":ruleForm.departmentId==4?"销售部":"行政部"}}
          
        </el-form-item>
      
        
        <el-form-item label="请假类别" prop="leaveTypeId">
          {{ ruleForm.leaveTypeName }}
        </el-form-item>

        <el-form-item label="请假时间" >
          <span class="newline-span">
            自 {{ ruleForm.startTime.substring(0,4) }} 年 {{ ruleForm.startTime.substring(5,7) }} 月 {{ ruleForm.startTime.substring(8,10) }} 日 {{ ruleForm.startTime.substring(11,13) }} 时 
            至 {{ ruleForm.endTime.substring(0,4) }} 年 {{ ruleForm.endTime.substring(5,7) }} 月 {{ ruleForm.endTime.substring(8,10) }} 日 {{ ruleForm.endTime.substring(11,13) }} 时
            <br>
          <span>共计{{ruleForm.days}}</span><br>
          <span>报道时间:
            {{ ruleForm.reportTime.substring(0,4) }} 年 {{ ruleForm.reportTime.substring(5,7) }} 月 {{ ruleForm.reportTime.substring(8,10) }} 日 {{ ruleForm.reportTime.substring(11,13) }} 时
           
          </span>
          </span>
        </el-form-item>

        <el-form-item label="请假事由" prop="reason">
          {{ ruleForm.reason }}
        </el-form-item>

        <el-form-item label="审核:" prop="">
          <el-radio-group v-model="ruleForm.state">
            <el-radio :value="2">通过</el-radio>
            <el-radio :value="3">不通过</el-radio>
            <el-input v-if="ruleForm.state==3" v-model="ruleForm.leaveReview" placeholder="原因?" style="width: 200px;"/>
          </el-radio-group>
          
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitFormShenHe(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
  </el-dialog>


</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMention, ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import moment from 'moment'
import {ElMessageBox, type ComponentSize } from 'element-plus'
import { pa } from 'element-plus/es/locales.mjs'
const size = ref<ComponentSize>('default')

import httpr from '@/axioslan/axioshttp'
import httpw from '@/axioslan/axioshttps'

interface User {
  date: string
  name: string
  address: string
}

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User
  rowIndex: number
}) => {
  if (rowIndex === 1) {
    return 'warning-row'
  } else if (rowIndex === 3) {
    return 'success-row'
  }
  return ''
}

onMounted(()=>{
  search();
})

let formInline:any=reactive
   ({
    statetime:'',
    endtime:'',
    state:'',
    leavename:''
   })
   let page:any=reactive
   ({
    pageindex:1,
    pagesize:15,
    totalCount:'',
    totalPage:''
   })
const tableData=ref([])

const search = () => {
  
  httpr({
    url: "/api/Leave/GetMyLeave",
    method: "get",
    params:
    {
      loginname:localStorage.getItem("userName"),
      statetime:formInline.statetime,
      endtime:formInline.endtime,
      state:formInline.state,
      leavename:formInline.leavename,
      pageindex:page.pageindex,
      pagesize:page.pagesize
    }
  }).then((res) => {
    console.log(formInline.statetime);
    console.log(formInline.endtime);
    
    tableData.value = res.data.pageDatas;
    page.totalCount=res.data.totalCount;
    page.totalPage=res.data.totalPage;
  });
};
 
watch(page,()=>
{
  search();
})


let currentloginname=localStorage.getItem("userName");
let courrentleaders=localStorage.getItem("leadersName")







//申请提交
const dialogTableVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const ruleForm:any = reactive({
  applicationName:localStorage.getItem("userName"),
  departmentId:localStorage.getItem("departmentId"),
  leaveTypeId:'',
  startTime: "",
  endTime: "",
  totalTime: '',
  reportTime: "",
  reason: "",
  depleaders: localStorage.getItem("leadersName"),
  days:'',
  leaveTypeName:'',
  state: '',
  leaveReview: ""
})

// // 如果需要精确计算（包括部分天数的小时数）
// const calculateTotalTime = () => {
//   if (!ruleForm.startTime || !ruleForm.endTime) return;
  

//   const start:any = new Date(ruleForm.startTime);
//   const end:any = new Date(ruleForm.endTime);

//   // 校验结束时间不能小于开始时间
//   if (end.getTime() < start.getTime()) {
//     ElMessage.error("结束时间不能小于开始时间");
//     ruleForm.endTime='';
//     return;
//   }
  
//   // 计算完整的小时数
//   const diffMs = Math.abs(end - start);
//   const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  
//   // 计算完整的天数部分
//   const fullDays = Math.floor(diffHours / 8);
//   const remainingHours = diffHours % 8;
  
//  // 更新ruleForm.totalTime（如果需要）
//  ruleForm.days = `${fullDays}天${remainingHours}时`;
//  ruleForm.totalTime=fullDays*8+remainingHours;
// };


const calculateTotalTime = () => {
  if (!ruleForm.startTime || !ruleForm.endTime) return;

  const start = new Date(ruleForm.startTime);
  const end = new Date(ruleForm.endTime);

  // 校验结束时间不能小于开始时间
  if (end.getTime() < start.getTime()) {
    ElMessage.error("结束时间不能小于开始时间");
    ruleForm.endTime = '';
    return;
  }

  // 定义工作时间段 (9:00-17:00)
  const workStartHour = 9;
  const workEndHour = 17;
  const dailyWorkHours = 8;

  let totalHours = 0;
  let current = new Date(start);

  // 遍历每一天
  while (current <= end) {
    const currentDay = new Date(current);
    currentDay.setHours(0, 0, 0, 0);

    // 当天的工作开始时间
    const dayStart = new Date(currentDay);
    dayStart.setHours(workStartHour);
    
    // 当天的工作结束时间
    const dayEnd = new Date(currentDay);
    dayEnd.setHours(workEndHour);

    // 计算当天的工作时间段
    let segmentStart:any = current > dayStart ? current : dayStart;
    let segmentEnd:any = end < dayEnd ? end : dayEnd;

   // 如果是同一天且在工作时间内
    if (segmentStart < segmentEnd) {
      const hours = Math.floor((segmentEnd - segmentStart) / (1000 * 60 * 60)); // 取整小时数
      totalHours += hours > 0 ? hours : 0; // 确保不为负数
    }

    // 移动到下一天
    current = new Date(currentDay);
    current.setDate(current.getDate() + 1);
    current.setHours(workStartHour, 0, 0, 0);
  }

  // 计算完整工作天数和剩余小时数
  const fullDays = Math.floor(totalHours / dailyWorkHours);
  const remainingHours = totalHours % dailyWorkHours;

  // 更新显示
  ruleForm.days = `${fullDays}天${remainingHours}时`;
  ruleForm.totalTime = fullDays*8+remainingHours; // 总小时数
};


const rules = reactive<FormRules>({
  
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      
      httpw
      ({
        url:'/api/Leave/CreateMyLeave',
        method:'post',
        data:ruleForm
      })
      .then(res=>{
        if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            search();
            dialogTableVisible.value=false;
            ruleForm.applicationName='',
            ruleForm.departmentId='',
            ruleForm.leaveTypeId=[],
            ruleForm.startTime='',
            ruleForm.endTime='',
            ruleForm.totalTime='',
            ruleForm.days="",
            ruleForm.reportTime='',
            ruleForm.reason='',
            ruleForm.depleaders=''
            return;
        }
        else
        {
            ElMessage.error(res.data.msg);
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


onMounted(()=>
{
    getleavetype();
})

//获取申请类别信息
let leavelist:any=ref([])
const getleavetype=()=>
{
    httpr
      ({
        url:'/api/Leave/GetLeaveType',
        method:'get'
      })
      .then(res=>{
        leavelist.value=res.data.data;

      })
}



//申请编辑
const dialogTableVisibleUpdate = ref(false)
const edit=(row:any)=>
{
  Object.assign(ruleForm,row);
  calculateTotalTime();
  dialogTableVisibleUpdate.value=true;
}
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      
      httpw
      ({
        url:'/api/Leave/UpdateLeave',
        method:'put',
        data:ruleForm
      })
      .then(res=>{
        if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            search();
            dialogTableVisibleUpdate.value=false;
            ruleForm.applicationName='',
            ruleForm.departmentId='',
            ruleForm.leaveTypeId=[],
            ruleForm.startTime='',
            ruleForm.endTime='',
            ruleForm.totalTime='',
            ruleForm.days="",
            ruleForm.reportTime='',
            ruleForm.reason='',
            ruleForm.depleaders=''
            return;
        }
        else
        {
            ElMessage.error(res.data.msg);
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


//删除申请
const Del=(id:any)=>
{
  ElMessageBox.confirm("您确认要删除申请信息吗?",
  "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      httpw({
        url: "/api/Leave/DeleteLeave",
        method: "delete",
        params: {
          id: id,
          loginname:localStorage.getItem("userName")
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          search();
          return;
        } else {
          ElMessage.error(res.data.msg);
          search();
          return;
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
}


//审核
const dialogTableVisibleShenHe = ref(false)
const shenhe=(row:any)=>
{
  Object.assign(ruleForm,row);
  calculateTotalTime();
  ruleForm.leaveTypeName=row.leaveTypeName;
  console.log(row.leaveTypeName);
  
   dialogTableVisibleShenHe.value=true;
}
const submitFormShenHe = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      
      httpw
      ({
        url:'/api/Leave/UpdateLeave',
        method:'put',
        data:ruleForm
      })
      .then(res=>{
        if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            search();
            dialogTableVisibleShenHe.value=false;
            ruleForm.applicationName='',
            ruleForm.departmentId='',
            ruleForm.leaveTypeId=[],
            ruleForm.startTime='',
            ruleForm.endTime='',
            ruleForm.totalTime='',
            ruleForm.days="",
            ruleForm.reportTime='',
            ruleForm.reason='',
            ruleForm.depleaders=''
            return;
        }
        else
        {
            ElMessage.error(res.data.msg);
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

</script>

<style>
.newline-span {
  white-space: pre-line; /* 或者 pre-wrap */
  display: inline-block; /* 可选，确保换行生效 */
  border: 1px solid #ccc; /* 仅用于演示边框 */
  padding: 10px;
}
</style>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>